import { useUserStore, useAuthStore } from '@/store'
import $api from '@/api'
//不需要token的路由
const WHITE_LIST = ['/login', '/404', "/403"]
//需要token 和 校长管理员权限的路由
// const PERMISSION_LIST = ["/user/teacher"]
const PERMISSION_LIST = []

export function createAuthGuard(router) {
  router.beforeEach(async (to) => {
    const authStore = useAuthStore()
    const token = authStore.accessToken


    /** 没有token */
    if (!token) {
      if (WHITE_LIST.includes(to.path))
        return true
      return { path: 'login', query: { ...to.query, redirect: to.path } }
    }

    // 有token的情况
    if (to.path === '/login')
      return { path: '/' }
    if (WHITE_LIST.includes(to.path))
      return true

    const userStore = useUserStore()

    // 没有用户信息 
    // if (!userStore.userInfo) {
    //   // const user = await $api.user.getUserBy()
    //   // userStore.setUser(user)
    //   return { ...to, replace: true }
    // }
    // 有用户信息，判断是否需要校长权限
    if (PERMISSION_LIST.includes(to.path) && !userStore.isAdmin) {
      return { path: '/403' }
    }
  })
}
